package com.ruoyi.web.controller.tool.designpattern.behavioralPatterns.mediator;

/**
 * 中介者模式
 *
 * @author Hack2003
 * @date 2024/3/21 17:36
 **/
// 1. 定义抽象同事类
 abstract class Colleague {
    protected Mediator mediator;

    public void setMediator(Mediator mediator) {
        this.mediator = mediator;
    }

    // 各个同事类需要实现的具体业务方法
    public abstract void send(String message);
    public abstract void receive(String message);
}

// 2. 具体同事类
 class ConcreteColleagueA extends Colleague {
    @Override
    public void send(String message) {
        System.out.println("ConcreteColleagueA 发送: " + message);
        mediator.send(message, this);
    }

    @Override
    public void receive(String message) {
        System.out.println("ConcreteColleagueA 收到: " + message);
    }
}

 class ConcreteColleagueB extends Colleague {
    @Override
    public void send(String message) {
        System.out.println("ConcreteColleagueB 发送: " + message);
        mediator.send(message, this);
    }

    @Override
    public void receive(String message) {
        System.out.println("ConcreteColleagueB 收到: " + message);
    }
}

// 3. 抽象中介者类
 interface Mediator {
    void send(String message, Colleague colleague);
    // 新增getter方法
    ConcreteColleagueA getColleagueA();
    ConcreteColleagueB getColleagueB();
}

// 4. 具体中介者类
 class ConcreteMediator implements Mediator {
    private ConcreteColleagueA colleagueA;
    private ConcreteColleagueB colleagueB;

    public ConcreteMediator() {
        colleagueA = new ConcreteColleagueA();
        colleagueB = new ConcreteColleagueB();

        colleagueA.setMediator(this);
        colleagueB.setMediator(this);
    }
    @Override
    public ConcreteColleagueA getColleagueA() {
        return colleagueA;
    }
    @Override
    public ConcreteColleagueB getColleagueB() {
        return colleagueB;
    }
    @Override
    public void send(String message, Colleague colleague) {
        if (colleague == colleagueA) {
            colleagueB.receive(message);
        } else if (colleague == colleagueB) {
            colleagueA.receive(message);
        }
    }
}

/**
 * 中介者模式（Mediator Pattern）是一种行为型设计模式，
 * 它通过定义一个中介对象来封装一系列的对象交互，
 * 从而使得各对象不需要显式地相互引用，降低了系统的耦合度
 */
public class Test {
    public static void main(String[] args) {
        Mediator mediator = new ConcreteMediator();
        ConcreteColleagueA colleagueA = mediator.getColleagueA();
        ConcreteColleagueB colleagueB = mediator.getColleagueB();

        colleagueA.send("你好！");
        colleagueB.send("嗨！");
    }
}

